package entity

import (
	"bili-server/app/cfg"
	"bili-server/app/log"
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

type Video struct {
	AID   string `json:"aid,omitempty"`
	Dir   string `json:"dir,omitempty"`
	DVI   *DVI   `json:"dvi,omitempty"`
	Cover string `json:"cover,omitempty"`
}

var (
	GlobVideos []*DVI

	MapVideos = map[string]*DVI{}
)

func init() {
	GlobVideos = GetVideos()
}

// DVI 一级目录的配置文件结构
type DVI struct {
	Aid                  string      `json:"Aid"`
	Bid                  string      `json:"Bid"`
	SeasonId             string      `json:"SeasonId"`
	EpisodeId            string      `json:"EpisodeId"`
	Title                string      `json:"Title"`
	Uploader             string      `json:"Uploader"`
	Mid                  string      `json:"Mid"`
	Description          string      `json:"Description"`
	CoverURL             string      `json:"CoverURL"`
	Tag                  interface{} `json:"Tag,omitempty"`
	DownloadTimeRelative int         `json:"DownloadTimeRelative"`
	CreateDate           string      `json:"CreateDate"`
	IsBangumi            bool        `json:"IsBangumi,omitempty"`
	Is360                bool        `json:"Is360,omitempty"`
	TotalTime            string      `json:"TotalTime"`
	Parts                interface{} `json:"Parts,omitempty"`
}

func read(dir string) (videos []*DVI) {
	d, err := os.ReadDir(dir)
	if err != nil {
		return
	}
	for _, entry := range d {
		if !entry.IsDir() {
			if strings.HasSuffix(entry.Name(), "dvi") {
				dvi, err := FromFile(fmt.Sprintf("%s/%s", dir, entry.Name()))
				if err != nil {
					continue
				}
				MapVideos[dvi.Aid] = dvi
				videos = append(videos, dvi)
			}
		}
	}
	return
}

func FromFile(filename string) (*DVI, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, nil
	}
	d := new(DVI)
	err = json.Unmarshal(data, d)
	return d, err
}

func GetVideos() (videos []*DVI) {
	config := cfg.GetConfig()
	for _, dir := range config.Dir {
		dirs, err := os.ReadDir(dir)
		if err != nil {
			log.L.Error("get videos err: ", err)
			continue
		}
		// 一级目录
		for _, entry := range dirs {
			if entry.IsDir() {
				v := read(fmt.Sprintf(fmt.Sprintf("%s/%s", dir, entry.Name())))
				videos = append(videos, v...)
			}
		}
	}
	return
}
